package com.mavenq.fly.utils;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class GenericTypeUtils {
    // 获取类定义的泛型类型（如获取父类泛型参数）
    public static Class<?> getGenericType(Class<?> clazz, int index) {
        Type type = clazz.getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            ParameterizedType pType = (ParameterizedType) type;
            Type[] actualTypes = pType.getActualTypeArguments();
            if (actualTypes.length > index) {
                return (Class<?>) actualTypes[index];
            }
        }
        throw new IllegalArgumentException("Generic type not found");
    }

    // 获取字段的泛型类型（如 List<String> 的 String）
    public static Class<?> getFieldGenericType(Field field, int index) {
        Type type = field.getGenericType();
        if (type instanceof ParameterizedType) {
            ParameterizedType pType = (ParameterizedType) type;
            Type[] actualTypes = pType.getActualTypeArguments();
            if (actualTypes.length > index) {
                return (Class<?>) actualTypes[index];
            }
        }
        throw new IllegalArgumentException("Field has no generic type");
    }
}